//
//  HMUIInputView.swift
//  HealthMonitoring
//
//  Created by YTYanK on 24/02/2019.
//  Copyright © 2019 YTYanK. All rights reserved.
//

import UIKit
import Photos

enum HMUIInputStatus {
    case text
    case microphone
    case photo
    case camera
    case emoji
    case none
    case custom
}

fileprivate var HMUIFeatureViewHeight:CGFloat = 215
fileprivate var HMUIFeatureSelectorHeight:CGFloat = 46
fileprivate var HMUIShowFeatureViewAnimationDuration = 0.25


class HMUIInputView: UIView {
    
    @objc open var inputTextViewPadding: UIEdgeInsets = UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8)
    @objc open var inputTextViewHeightRange: UIFloatRange = UIFloatRange.init(minimum: 20, maximum: 60)
    
    @objc open var inputTextViewTextColor: UIColor = UIColor(netHex: 0x555555)
    @objc open var inputTextViewFont: UIFont = UIFont.systemFont(ofSize: 20)
    
    // 数据？
    var featureListDataSource:[IMUIFeatureIconModel] = [IMUIFeatureIconModel]()
     open var currentFeature: IMUIFeatureType = .none
    
    var inputViewStatus: HMUIInputStatus = .none
    // ？？
    @objc open weak var inputViewDelegate: IMUIInputViewDelegate? {
        didSet {
            self.featureView.inputViewDelegate = self.inputViewDelegate
        }
    }
    
    // 控制器
    private lazy var collView: UICollectionView = {
        
        var layout = UICollectionViewFlowLayout.init()
        layout.scrollDirection = UICollectionViewScrollDirection.vertical
        let _vie = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        _vie.collectionViewLayout = layout
        
        _vie.delegate = self
        _vie.dataSource = self
        _vie.backgroundColor = .clear
        _vie.register(HMIconView.classForCoder(), forCellWithReuseIdentifier: "HMIconView")
//        _vie.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "cellid")
        return _vie
    }()
    /// 判断是否更多
    var isCollView = false
    
    
    @IBOutlet var view: UIView!
    // 控制内容栏高度
    @IBOutlet weak var moreViewHeight: NSLayoutConstraint!
    @IBOutlet weak var inputTextViewHeight: NSLayoutConstraint!
    
    // 控制器获取 IM 控制器
    var messageCollectionView:IMUIMessageCollectionView?
    var conversation: TIMConversation?
    var instantMess: InstantMessaging?
    
    // 图标列表
   // @IBOutlet open weak var featureSelectorView: IMUIFeatureListView!
    var iconList = Array<String>()
    // 内容栏
    @IBOutlet open weak var featureView: IMUIFeatureView!
    // 输入框
    @IBOutlet open weak var inputTextView: UITextView!
    @IBOutlet weak var micBtn: UIButton!
    @IBOutlet weak var photoBtn: UIButton!
    @IBOutlet weak var cameraBtn: UIButton!
    @IBOutlet weak var sendBtn: UIButton!
    // 更多
    @IBOutlet open weak var moreBtn: UIButton!
    // 表情
    @IBOutlet open weak var emojiBtn: UIButton!
    // 语音
    @IBOutlet open weak var soundBtn: UIButton!
    
    
    @IBOutlet weak var paddingLeft: NSLayoutConstraint!
    @IBOutlet weak var paddingRight: NSLayoutConstraint!
    @IBOutlet weak var paddingTop: NSLayoutConstraint!
    @IBOutlet weak var paddingBottom: NSLayoutConstraint!
    // soundBtn 与 input 间距
    @IBOutlet weak var spacingSoundOrInuput: NSLayoutConstraint!
    // emojiBtn 与 Input 间距
    @IBOutlet weak var spacingInputOrEmoji: NSLayoutConstraint!
    // emoji 与 moreBtn 间距
    @IBOutlet weak var spacingEmojiOrMore: NSLayoutConstraint!
    
    
    
    override public init(frame: CGRect) {
        super.init(frame: frame)
//        let bundle = Bundle.imuiInputViewBundle()
//        view = (bundle.loadNibNamed("HMUIInputView", owner: self, options: nil)?.first as! UIView)
//
//        self.addSubview(view)
//        view.frame = self.bounds
//
//        self.inputTextView.textContainer.lineBreakMode = .byWordWrapping
//        self.inputTextView.font = UIFont.systemFont(ofSize: 14)
//        self.inputTextView.textColor = inputTextViewTextColor
//        self.inputTextView.layoutManager.allowsNonContiguousLayout = false
//        self.inputTextView.delegate = self
//        self.featureView.delegate = self
    }
    
    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        
        // 设置数据
//        self.setupAllData()
        self.iconList = ["退单", "图片", "拍摄","药物建议","药物建议","药物建议","药物建议","药物建议"] as! [String]
        
        
        let bundle = Bundle.imuiInputViewBundle()  //IMUIInputView
        view = bundle.loadNibNamed("HMUIInputView", owner: self, options: nil)?.first as! UIView
        self.addSubview(view)
        view.frame = self.bounds
        
        inputTextView.textContainer.lineFragmentPadding = 0
        inputTextView.textContainerInset = .zero
        inputTextView.font = inputTextViewFont
        inputTextView.textColor = inputTextViewTextColor
        inputTextView.layoutManager.allowsNonContiguousLayout = false

        inputTextView.textContainer.lineBreakMode = .byWordWrapping
        inputTextView.returnKeyType = .send
        inputTextView.delegate = self
        self.featureView.delegate = self
        

        soundBtn.backgroundColor = UIColor.clear
        soundBtn.layer.borderWidth = 1.5
        soundBtn.layer.cornerRadius = 18
        soundBtn.heightConstrain(predicate: "36")
        soundBtn.widthConstrain(predicate: "36")
        soundBtn.addTarget(self, action: #selector(soundClick), for: UIControlEvents.touchUpInside)
        let soundImage = UIImage.imuiImage(with: "input_item_mic")?.withRenderingMode(.alwaysTemplate)
        soundBtn.tintColor = .black
        soundBtn.setImage(soundImage, for: UIControlState.normal)
        soundBtn.setImage(soundImage, for: UIControlState.highlighted)
        
        
        emojiBtn.backgroundColor = UIColor.clear
        emojiBtn.layer.borderWidth = 1.5
        emojiBtn.layer.cornerRadius = 18
        emojiBtn.heightConstrain(predicate: "36")
        emojiBtn.widthConstrain(predicate: "36")
        emojiBtn.addTarget(self, action: #selector(emojiClick), for: UIControlEvents.touchUpInside)
        let emojiImage = UIImage.init(named: "笑脸")?.withRenderingMode(.alwaysTemplate)
        emojiBtn.tintColor = .black
        emojiBtn.setImage(emojiImage, for: UIControlState.normal)
        emojiBtn.setImage(emojiImage, for: UIControlState.highlighted)
        
        
        moreBtn.backgroundColor = UIColor.clear
        moreBtn.layer.borderWidth = 1.5
        moreBtn.layer.cornerRadius = 18
        moreBtn.heightConstrain(predicate: "36")
        moreBtn.widthConstrain(predicate: "36")
        moreBtn.addTarget(self, action: #selector(moreClick), for: UIControlEvents.touchUpInside)
        let moreImage = UIImage.init(named: "加")?.withRenderingMode(.alwaysTemplate)
        moreBtn.tintColor = .black
        moreBtn.setImage(moreImage, for: UIControlState.normal)
        moreBtn.setImage(moreImage, for: UIControlState.highlighted)
    }
    

    
    @objc func soundClick(_ sender: UIButton) {
        self.clickMicBtn(btn: sender)
    }
    
    @objc func moreClick(_ sender: UIButton) {
        print("更多？？")
        
        self.inputTextView.resignFirstResponder()
        DispatchQueue.main.async {
            self.featureView.layoutFeature(with: .none)
        }
        
        self.showFeatureView()
        self.addMoreIcon()
  
    }
    

    
    func addMoreIcon() {
        self.isCollView = true
        self.featureView.addSubview(self.collView)
        self.collView.topAlign(view: self.featureView, predicate: "10")
        self.collView.bottomAlign(view: self.featureView, predicate: "-10")
        self.collView.leadingAlign(view: self.featureView, predicate: "0")
        self.collView.trailingAlign(view: self.featureView, predicate: "0")
    }
    
    func removeMoreIcon() {
        self.collView.removeFromSuperview()
    }
    
    
    @objc func emojiClick(_ sender: UIButton) {
        self.clickEmojiBtn(btn: sender)
    }
    // 初始化
    open override func awakeFromNib() {
        super.awakeFromNib()
        
        // 监控s键盘改变时
//        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardFrameChanged(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        // 显示
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWithShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        // 隐藏
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWithHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        
        
        self.inputTextViewHeight.constant =  36.0
        //  IMUIEmojiCell
        self.paddingLeft.constant = self.inputTextViewPadding.left
        self.paddingRight.constant = self.inputTextViewPadding.right
        self.paddingTop.constant = self.inputTextViewPadding.top
        self.paddingBottom.constant = self.inputTextViewPadding.bottom
    }
    // 键盘改变时
    @objc func keyboardFrameChanged(_ notification: Notification) {
        
        let dic = NSDictionary(dictionary: (notification as NSNotification).userInfo!)
        let keyboardValue = dic.object(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
        let bottomDistance = UIScreen.main.bounds.size.height  - keyboardValue.cgRectValue.origin.y
        let duration = Double(dic.object(forKey: UIKeyboardAnimationDurationUserInfoKey) as! NSNumber)
            UIView.animate(withDuration: duration) {
                if bottomDistance > 10.0 {
//                    print("HMUIFeatureViewHeight===>", bottomDistance)
                    HMUIFeatureViewHeight  = bottomDistance
                    self.moreViewHeight.constant = HMUIFeatureViewHeight
                    self.inputViewDelegate?.keyBoardWillShow?(height: keyboardValue.cgRectValue.size.height, durationTime: duration)
                    
                }
            }
    }
    
    
    @objc func keyboardWithShow(_ notification: Notification) {
        print("显示")
        self.showFeatureView()
        if isCollView ==  true {
            self.isCollView = false
            self.removeMoreIcon()
        }
        let dic = NSDictionary(dictionary: (notification as NSNotification).userInfo!)
        let keyboardValue = dic.object(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
        let bottomDistance = UIScreen.main.bounds.size.height  - keyboardValue.cgRectValue.origin.y
        let duration = Double(dic.object(forKey: UIKeyboardAnimationDurationUserInfoKey) as! NSNumber)
        self.inputViewDelegate?.keyBoardWillShow?(height: keyboardValue.cgRectValue.size.height, durationTime: duration)
    }
    @objc func keyboardWithHide(_ notification: Notification) {
        print("隐藏")
        self.hideFeatureView()
       
    }
    
    func leaveGalleryMode() {
        if isCollView ==  true {
            self.isCollView = false
            self.removeMoreIcon()
        }
        featureView.clearAllSelectedGallery()
        self.updateSendBtnToPhotoSendStatus()
    }
    
    
    // 输入框自适应
    @objc public func layoutInputView() {
        self.fitTextViewSize(self.inputTextView)
    }
    func fitTextViewSize(_ textView: UITextView) {
        let textViewFitSize = textView.sizeThatFits(CGSize(width: textView.imui_width, height: CGFloat(MAXFLOAT)))
        if textViewFitSize.height <= inputTextViewHeightRange.minimum {
            self.inputTextViewHeight.constant = inputTextViewHeightRange.minimum
            return
        }
        
        let newValue = textViewFitSize.height > inputTextViewHeightRange.maximum ? inputTextViewHeightRange.maximum : textViewFitSize.height
        if newValue != self.inputTextViewHeight.constant {
            self.inputTextViewHeight.constant = 120
            DispatchQueue.main.async {
                self.inputTextViewHeight.constant = newValue
                textView.scrollRangeToVisible(NSRange(location: 0, length: 0))
            }
        }
    }
    
    
    /// 内容显示
    @objc open func showFeatureView() {
        UIView.animate(withDuration: HMUIShowFeatureViewAnimationDuration) {
            self.moreViewHeight.constant = 253
            self.superview?.layoutIfNeeded()
        }
    }
    //隐藏内容
    @objc public func hideFeatureView() {
        UIView.animate(withDuration: HMUIShowFeatureViewAnimationDuration) {
            self.moreViewHeight.constant = 0
            self.inputTextView.resignFirstResponder()
            self.featureView.currentType = .none
            self.featureView.featureCollectionView.reloadData()
            self.superview?.layoutIfNeeded()
        }
    }
    
    deinit {
        self.featureView.clearAllSelectedGallery()
        NotificationCenter.default.removeObserver(self)
    }
}


// MARK: - UITextViewDelegate
extension HMUIInputView: UITextViewDelegate {
    public func textViewDidChange(_ textView: UITextView) {
        self.fitTextViewSize(textView)
        self.updateSendBtnToPhotoSendStatus()
        self.inputViewDelegate?.textDidChange?(text: textView.text)
    }
    public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        inputViewStatus = .text
        return true
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if  text.elementsEqual("\n") { //判断输入的字是否是回车，即按下return
            textView.resignFirstResponder()
            self.clickSendBtn()
            return false; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
        }
        return true
    }
}

// 选择图标时的代理
extension HMUIInputView {

   
//    public func onClickSend(with cell: IMUIFeatureListIconCell) {
////        self.clickSendBtn(cell:cell)
//    }
    // 语音
    func clickMicBtn(btn: UIButton) {
        self.leaveGalleryMode()
        inputViewStatus = .microphone
        self.inputTextView.resignFirstResponder()
        self.inputViewDelegate?.switchToMicrophoneMode?(recordVoiceBtn: btn)
        let serialQueue = DispatchQueue.init(label: "inputview")
        serialQueue.async {
            usleep(10000)
            DispatchQueue.main.async {
                self.featureView.layoutFeature(with: .voice)
                self.showFeatureView()
            }
        }
    }
    // 自定义内容
    func clickCustomBtn(btn: UIButton, type: String) {
        UserDefaults.standard.set(type, forKey: "sendCustom")
        inputViewStatus = .none
        self.inputTextView.resignFirstResponder()
        
        //添加内容
        let jsonData = Data()
        let outGoingmessage = MessageModel(data: jsonData, isOutGoing: true, type: "药物建议")
          outGoingmessage.messageStatus = .sending
        HMElem.structureMessage(self.conversation!, elemType: TIMCustomElem.classForCoder(), value: jsonData, succ: {
            outGoingmessage.messageStatus = .success
             self.messageCollectionView?.appendMessage(with: outGoingmessage)
        }) { (code, err) in
            outGoingmessage.messageStatus = .failed
             self.messageCollectionView?.appendMessage(with: outGoingmessage)
        }
       
    }
    // 药品建议
    func clickGoDrugs() {
        self.leaveGalleryMode()
        inputViewStatus = .none
        self.hideFeatureView()
        
        let  pr = HMProposalAll()
        pr.title = "档案管理"
//        pr.isRemindType = "data"
        self.instantMess!.pushViewController(pr)
        
    }
    
    // 相册
    func clickPhotoBtn(btn: UIButton) {
        self.leaveGalleryMode()
        inputViewStatus = .photo
        
        inputTextView.resignFirstResponder()
        inputViewDelegate?.switchToGalleryMode?(photoBtn: btn)
        DispatchQueue.main.async {
            self.featureView.layoutFeature(with: .gallery)
        }
        self.showFeatureView()
    }
    
    // 照相机
    func clickCameraBtn(btn: UIButton) {
        self.leaveGalleryMode()
        inputViewStatus = .camera
        
        inputTextView.resignFirstResponder()
        inputViewDelegate?.switchToCameraMode?(cameraBtn: btn)
        DispatchQueue.main.async {
            self.featureView.layoutFeature(with: .camera)
        }
        self.showFeatureView()
    }
    
    // 表情
    func clickEmojiBtn(btn: UIButton) {
       self.leaveGalleryMode()
       inputViewStatus = .emoji
       inputTextView.resignFirstResponder()
       inputViewDelegate?.switchToEmojiMode?(cameraBtn: btn)
        DispatchQueue.main.async {
            self.featureView.layoutFeature(with: .emoji)
        }
        self.showFeatureView()
    }

    // 发送
    func clickSendBtn() {
        if IMUIGalleryDataManager.selectedAssets.count > 0 {
            self.inputViewDelegate?.didSeletedGallery?(AssetArr: IMUIGalleryDataManager.selectedAssets)
            self.featureView.clearAllSelectedGallery()
            self.updateSendBtnToPhotoSendStatus()
            return
        }
        
        if inputTextView.text != "" {
            inputViewDelegate?.sendTextMessage?(self.inputTextView.text)
            inputTextView.text = ""
            self.inputViewDelegate?.textDidChange?(text: "")
            fitTextViewSize(inputTextView)
        }
        
        self.updateSendBtnToPhotoSendStatus()
    }
    
}


extension HMUIInputView: IMUIFeatureViewDelegate {
    
    public func cameraRecoverScreen() {
        self.inputViewDelegate?.cameraRecoverScreen?()
    }
    
    public func cameraFullScreen() {
        self.inputViewDelegate?.cameraFullScreen?()
    }
    
    public func didChangeSelectedGallery(with gallerys: [PHAsset]) {
        self.updateSendBtnToPhotoSendStatus()
    }
    
    public func updateSendBtnToPhotoSendStatus() {
        var isAllowToSend = false
        var seletedPhotoCount = IMUIGalleryDataManager.selectedAssets.count
        if seletedPhotoCount > 0 {
            isAllowToSend = true
        }
        
        if inputTextView.text != "" {
            isAllowToSend = true
        }
        
//        self.featureSelectorView.updateSendButton(with: seletedPhotoCount, isAllowToSend: isAllowToSend)
    }
    
    public func didSelectPhoto(with images: [UIImage]) {
        self.updateSendBtnToPhotoSendStatus()
    }

    public func didSeletedEmoji(with emoji: IMUIEmojiModel) {
        switch emoji.emojiType {
        case .emoji:
            let inputStr = "\(self.inputTextView.text!)\(emoji.emoji!)"
            self.inputTextView.text = inputStr
            self.fitTextViewSize(self.inputTextView)
            self.updateSendBtnToPhotoSendStatus()
            self.inputViewDelegate?.textDidChange?(text: inputStr)
        default:
            return
        }
    }
    
    public func didRecordVoice(with voicePath: String, durationTime: Double) {
        self.inputViewDelegate?.finishRecordVoice?(voicePath, durationTime: durationTime)
    }
    
    public func didShotPicture(with image: Data) {
        self.inputViewDelegate?.didShootPicture?(picture: image)
    }
    
    public func didRecordVideo(with videoPath: String, durationTime: Double) {
        self.inputViewDelegate?.finishRecordVideo?(videoPath: videoPath, durationTime: durationTime)
    }
}


extension HMUIInputView: UICollectionViewDelegate {
    
}

extension HMUIInputView: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.iconList.count
    }
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
       // collectionView.collectionViewLayout.invalidateLayout()
        return 1
    }
    
    public func collectionView(_ collectionView: UICollectionView,
                               layout collectionViewLayout: UICollectionViewLayout,
                               sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let scrWidth =  UIScreen.main.bounds.size.width //- 10 // 减一个10间距
        let width = scrWidth / 4.0 - 50.0 / 4.0
        
        return CGSize(width: width, height: width)
    }
    
    public func collectionView(_ collectionView: UICollectionView,
                               layout collectionViewLayout: UICollectionViewLayout,
                               referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(10, 10, 10, 10)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    
    public func collectionView(_ collectionView: UICollectionView,
                               cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellIdentifier = "HMIconView"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! HMIconView
        cell.updateDate(str: iconList[indexPath.row])
        cell.onClickCallBack = {
            (view) -> () in
            let iconStr = view.btn.titleLabel?.text
            if iconStr == "退单" {
                
            }else if iconStr == "图片" {
                self.clickPhotoBtn(btn: view.btn)
            }else if iconStr == "拍摄" {
                self.clickCameraBtn(btn: view.btn)
            }else if iconStr == "药物建议" {
                  self.clickGoDrugs()
//                self.clickCustomBtn(btn: view.btn, type: iconStr!)
            }else {
                
            }
        }
//        let r = CGFloat(arc4random() % UInt32(255.0)) / 255.0
//        let b = CGFloat(arc4random() % UInt32(255.0)) / 255.0
//        let g = CGFloat(arc4random() % UInt32(255.0)) / 255.0
//         cell.backgroundColor = UIColor.init(red: r, green: g, blue: b, alpha: 1)  //RGBA(r: r, g: g, b: b, a: 1)
        return cell
    }
    
    
    
}
